package com.metal.gear.certification.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.metal.gear.certification.entity.dto.SysRoleSaveAndEditDto;
import com.metal.gear.certification.entity.dto.SysRoleSearchDto;
import com.metal.gear.certification.entity.dto.permission.RolePermissionSaveDto;
import com.metal.gear.certification.entity.po.SysRole;
import com.metal.gear.certification.entity.po.SysRolePermission;
import com.metal.gear.certification.service.ISysPermissionService;
import com.metal.gear.certification.service.ISysRolePermissionService;
import com.metal.gear.certification.service.ISysRoleService;
import com.metal.gear.common.entity.Result;
import com.metal.gear.common.exception.SzlBusinessException;
import com.metal.gear.common.util.query.SearchHelper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Tag(name = "3.角色管理")
@RestController
@RequestMapping("/sys/role")
@Slf4j
public class SysRoleController {
    @Autowired
    private ISysRoleService sysRoleService;


    @Autowired
    private ISysRolePermissionService sysRolePermissionService;

    @Autowired
    private ISysPermissionService sysPermissionService;


    @Operation(summary = "分页列表查询", description = "用于角色管理分页展示列表")
    @ApiOperationSupport(order = 1)
    @GetMapping(value = "/a/list",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<IPage<SysRole>> queryPageList(SysRoleSearchDto searchDto,
                                                @RequestParam(defaultValue = "1") Integer pageNo,
                                                @RequestParam(defaultValue = "10") Integer pageSize) throws Exception {
        QueryWrapper<SysRole> queryWrapper = SearchHelper.generalQueryWrapper(searchDto);
        Page<SysRole> page = Page.of(pageNo, pageSize);
        return Result.ok(sysRoleService.page(page, queryWrapper));
    }

    @Operation(summary ="查询所有角色")
    @ApiOperationSupport(order = 1)
    @GetMapping(value = "/a/queryall",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<List<SysRole>> queryall() {
        return Result.ok(sysRoleService.list());
    }

    @Operation(summary ="查询角色详细信息")
    @ApiOperationSupport(order = 1)
    @GetMapping(value = "/a/queryById",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<SysRole> queryById(@RequestParam String roleId) {
        return Result.ok(sysRoleService.getById(roleId));
    }

    @Operation(summary ="校验角色编码唯一")
    @ApiOperationSupport(order = 2)
    @RequestMapping(value = "/a/checkRoleCode", method = RequestMethod.GET,produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> checkUsername(String id, String roleCode) {
        if (StrUtil.isNotEmpty(id)) {
            //否则=>编辑模式=>判断两者ID是否一致-
            return Result.ok(Objects.isNull((sysRoleService.getByRoleCodeAndNotEqId(id, roleCode))));
        } else {
            //role为空=>新增模式=>只要roleCode存在则返回false
            return Result.ok(Objects.isNull((sysRoleService.getByRoleCode(roleCode))));
        }

    }

    @Operation(summary ="添加角色")
    @ApiOperationSupport(order = 2)
    @PostMapping(value = "/a/add",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> add(@RequestBody SysRoleSaveAndEditDto roleDto) {
        SysRole sysRole = SysRoleSaveAndEditDto.translateTo(roleDto);
        return Result.ok("添加角色成功", sysRoleService.save(sysRole));

    }

    @Operation(summary ="编辑角色")
    @ApiOperationSupport(order = 3)
    @PutMapping(value = "/a/edit",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> edit(@RequestBody SysRoleSaveAndEditDto roleDto) {
        SysRole sysRole = SysRoleSaveAndEditDto.translateTo(roleDto);
        return Result.ok(sysRoleService.updateById(sysRole));
    }


    @Operation(summary ="删除角色")
    @ApiOperationSupport(order = 4)
    @DeleteMapping(value = "/a/delete",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> delete(@RequestParam String id) {
        return Result.ok("删除角色成功", sysRoleService.deleteRole(id));
    }

    @Operation(summary ="批量删除角色")
    @ApiOperationSupport(order = 5)
    @DeleteMapping(value = "/a/deleteBatch",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> deleteBatch(@RequestParam  String ids) {
        return Result.ok("删除角色成功!", sysRoleService.deleteBatchRole(ids.split(",")));
    }





    @Operation(summary ="导出角色")
    @ApiOperationSupport(order = 6)
    @RequestMapping(value = "/a/exportXls" ,produces = {MediaType.APPLICATION_JSON_VALUE})
    public ModelAndView exportXls(SysRole sysRole, HttpServletRequest request) throws Exception {
        throw new Exception("接口未实现");
    }


    @Operation(summary ="导入数据")
    @ApiOperationSupport(order = 7)
    @RequestMapping(value = "/a/importExcelProperty", method = RequestMethod.POST ,produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<?> importExcelProperty(HttpServletRequest request, HttpServletResponse response) throws Exception {
        throw new Exception("接口未实现");

    }


    @Operation(summary ="查询角色授权")
    @ApiOperationSupport(order = 8)
    @GetMapping(value = "/d/queryRolePermission",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<List<String>> queryRolePermission(@RequestParam String roleId) {
        try {
            return Result.ok(
                    sysRolePermissionService.listByRoleId(roleId).stream()
                            .map(SysRolePermission::getPermissionId)
                            .collect(Collectors.toList())
            );
        } catch (Exception e) {
            throw new SzlBusinessException("查询角色授权失败", e);
        }
    }

    @Operation(summary ="角色授权")
    @ApiOperationSupport(order = 9)
    @PostMapping(value = "/d/saveRolePermission",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> saveRolePermission(@RequestBody RolePermissionSaveDto saveDto) {
//        try {
//            sysRolePermissionService.saveRolePermission(saveDto.getRoleId(), saveDto.getPermissionIdList());
//            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//            return Result.ok("保存授权成功！");
//        } catch (Exception e) {
//            throw new SzlBusinessException("角色授权失败", e);
//        }
        return Result.ok();
    }


}
